package edu.hziee.controllers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import edu.hziee.dao.UserDao;
import edu.hziee.models.User;

@Controller
@RequestMapping("/login")
public class LoginController {

	@Autowired
	private UserDao userDao;

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView get() {
		return new ModelAndView("login/login");
	}

	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView post(HttpSession session, HttpServletRequest req, @RequestParam String userName,
			@RequestParam String password, @RequestParam(required = false) String returnUrl) {
		User user = new User();
		user = userDao.findByName(userName);

		if (user == null) {
			ModelAndView mav = new ModelAndView("login/login");
			mav.addObject("error", "该用户不存在!");
			return mav;
		}
		if (userName.equals(user.getUserName()) && password.equals(user.getPassword())) {
			session.setAttribute("userName", userName);
			if (returnUrl != null)
			/*	if(returnUrl == "register")
					return new ModelAndView("redirect: login/register");
				else*/
					return new ModelAndView("redirect:" + returnUrl.replace(req.getContextPath(), ""));

			else
				return new ModelAndView("redirect: book");

		} else {
			ModelAndView mav = new ModelAndView("login/login");
			mav.addObject("error", "用户名或者密码错误!");
			return mav;

		}
	}

}
